package main

import (
	"crossrun.top/model"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strings"
	"time"

	"crossrun.top/control"
	"crossrun.top/service"
)

func main() {
	//打印IP
	ipInternal()
	//	MMain()

	//检查本地存放目录
	_dir := []string{"../files", "../files/blog", "../files/about"}
	checkAndMkDir(_dir)

	//初始化数据库
	err := control.Initdb()
	if err != nil {
		log.Fatal("db error: ", err)
	}
	//	testAddBlog()
	//	testUpdataBlog()
	//	testBlogList()
	//	testAddCatalog()
	//	testCataList()
	//	testListBlogByCat()

	httpStart()
}

func testAddCatalog() {
	c, err := control.AddCatalog("测试一", 1)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(c)
	}

}

func testListBlogByCat() {
	blogs, _ := control.ListBlogByCat("1", 1, 10)

	for i := 0; i < len(blogs); i++ {
		fmt.Println(blogs[i])
	}
}

func testUpdataBlog() {
	var cat model.Catalog
	cat.Id = "1"

	var blog model.Blog
	blog.Id = "3"
	blog.Cata = cat
	blog.Content = "测试=xiugai"
	blog.Title = "测试标题=xiugai"
	blog.Modification = time.Now().UnixNano() / 1e6
	err := control.UpdateBlog(blog)
	if err != nil {
		fmt.Println(err)
	}
}

func testAddBlog() {
	var cat model.Catalog
	cat.Id = "1"

	var blog model.Blog
	blog.Cata = cat
	blog.Content = "测试"
	blog.Title = "测试标题"
	blog.Time = time.Now().UnixNano() / 1e6
	blog.Modification = blog.Time
	err := control.AddBlog(blog)
	if err != nil {
		fmt.Println(err)
	}
}

func testCataList() {
	cats, _ := control.ListCataLog()

	for i := 0; i < len(cats); i++ {
		fmt.Println(cats[i])
	}
}

func testBlogList() {
	blogs, _ := control.ListBlog(1, 10)

	for i := 0; i < len(blogs); i++ {
		fmt.Println(blogs[i])
	}
}

func ipInternal() {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		os.Stderr.WriteString("Oops:" + err.Error())
		os.Exit(1)
	}
	for _, a := range addrs {
		if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				os.Stdout.WriteString(ipnet.IP.String() + "\n")
			}
		}
	}
}

// 判断文件夹是否存在
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

// 创建文件夹
func PathMk(path string) bool {
	fmt.Printf("no dir![%v]\n", path)
	err := os.Mkdir(path, os.ModePerm)
	if err != nil {
		fmt.Printf("mkdir failed![%v]\n", err)
	} else {
		fmt.Printf("mkdir success!\n")
	}
	return err == nil
}

//批量检查并创建目录
func checkAndMkDir(dirs []string) {
	for _, dir := range dirs {
		exist, err := PathExists(dir)
		if err != nil {
			fmt.Printf("get dir error![%v]\n", err)
			return
		}
		if exist {
			fmt.Printf("has dir![%v]\n", dir)
		} else {
			if !PathMk(dir) {
				log.Fatal("Make dir failed")
			}
		}
	}
}


func IndexOpHtml(w http.ResponseWriter, r *http.Request) {
	//	file := "h://" + r.URL.Path
	fmt.Println("this ope")
	http.ServeFile(w, r, "./static/about.html")
}

func indexHtml(w http.ResponseWriter, r *http.Request) {
	//	fmt.Println(r.URL.Path)
	if strings.Compare(r.URL.Path, "/") == 0 {
		fmt.Println("index")
		http.ServeFile(w, r, "./static/index.html")
	} else {
		fmt.Println("./static" + r.URL.Path)
		http.ServeFile(w, r, "./static"+r.URL.Path)
	}
}

func newHtml(w http.ResponseWriter, r *http.Request) {
	//	fmt.Println(r.URL.Path)
	http.ServeFile(w, r, "./static/blogeditor.html")
}

func blogHtml(w http.ResponseWriter, r *http.Request) {
	//	fmt.Println(r.URL.Path)
	http.ServeFile(w, r, "./static/blog.html")
}

func httpStart() {
		http.HandleFunc("/ope", IndexOpHtml)
		http.HandleFunc("/api/saveblog", service.SaveBlog)
		http.HandleFunc("/api/catas", service.ListCatalog)

	http.HandleFunc("/api/blog/add", service.SaveBlog)
	http.HandleFunc("/api/blog/list", service.ListBlog)
	http.HandleFunc("/api/blog/blog", service.Blog)
	http.HandleFunc("/api/catalog/list", service.ListCatalog)
	http.HandleFunc("/api/catalog/add", service.AddCatalog)
	http.HandleFunc("/blog", blogHtml)
	http.HandleFunc("/new", newHtml)
	http.HandleFunc("/", indexHtml)

	err := http.ListenAndServe(":9393", nil) //设置监听的端口
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
